<template>
    <div class="addDialog">
        <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" v-model="visible" title=""
            :show-close="false" align-center class="dialogAdd">
            <div class="dialog_content">
                <div class="dialog_header">
                    <div class="title">
                        <img src="@/assets/images/rectangle07.png" alt="">
                        <span>{{ props.type_dialog == 'add' ? '新增' : '编辑' }}</span>
                        <span v-if="checkItem.level == 0">班组类别</span>
                        <span v-if="checkItem.level == 1">班组</span>
                        <span v-if="checkItem.level == 2">班组成员</span>
                    </div>
                    <!-- <img class="close" src="@/assets/images/close.png" @click="handleClose" alt=""> -->
                </div>
                <div class="dialog_details">
                    <div class="details">
                        <template v-if="checkItem.level < 2">
                            <el-form ref="ruleFormRef" class="dialog_form" :model="ruleFormData.ruleForm"
                                :rules="rules">
                                <template v-if="checkItem.level == 0">
                                    <el-form-item label="班组类别" prop="name">
                                        <el-input v-model.trim="ruleFormData.ruleForm.name" placeholder=""></el-input>
                                    </el-form-item>
                                </template>
                                <template v-else-if="checkItem.level == 1">
                                    <el-form-item label="班组名称" prop="name">
                                        <el-input v-model.trim="ruleFormData.ruleForm.name" placeholder=""></el-input>
                                    </el-form-item>
                                    <el-form-item label="班组组长" prop="userList">
                                        <deviceType_select :edit="type_dialog" :selectData="ruleFormData.selectData"
                                            ref="selectComponent" @getDeviceTypeId="getDeviceTypeId">
                                        </deviceType_select>
                                    </el-form-item>
                                </template>
                                <el-form-item class="item_btn">
                                    <div class="btn">
                                        <el-button type="warning" @click="handleConfirm(ruleFormRef)">保 存</el-button>
                                        <el-button @click="handleClose">取 消</el-button>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </template>
                        <template v-else>
                            <el-form ref="ruleFormRef2" class="dialog_form" :model="ruleFormData.ruleForm2"
                                :rules="rules2">
                                <el-form-item label="班组成员" prop="userList">
                                    <deviceType_select :edit="type_dialog" ref="selectComponent2" @getDeviceTypeId="getDeviceTypeId2">
                                    </deviceType_select>
                                </el-form-item>
                                <el-form-item class="item_btn">
                                    <div class="btn">
                                        <el-button type="warning" @click="handleConfirm2(ruleFormRef2)">保 存</el-button>
                                        <el-button @click="handleClose">取 消</el-button>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </template>


                    </div>
                </div>
            </div>

        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { schedulingGroupAdd, schedulingGroupEdit,addMembers } from "@/http/scheduling"
import type { FormInstance, FormRules } from 'element-plus'
import deviceType_select from "./deviceType_select.vue";

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    type_dialog: { //add 新增 edit 编辑
        type: String,
        default: ''
    },
    dialogParams: {
        type: Object as any,
        default: {}
    },
    checkItem: {
        type: Object as any,
        default: {}
    }
})
let visible = ref(false);

const treeValue = ref<any[]>([]); //空间分类的值


const ruleFormRef = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()

interface IuserList {
    userId: Number;
    userName: String;
}
interface IruleForm {
    id?: string;
    level?: number;
    name: string;
    parentId?: number;
    userList?: Array<IuserList>;
}
interface IuserList2 {
    userId: Number;
    userName: String;
}
interface IruleForm2 {
    groupId?: string;
    userList?: Array<IuserList2>;
}
const ruleFormData = reactive({
    ruleForm: {
        level: 0,
        name: "",
        parentId: 0
    } as IruleForm,
    ruleForm2: {
        groupId: "",
        userList: []
    } as IruleForm2,
    selectData: [] as any,
})

let selectComponent = ref<any>(null);
let selectComponent2 = ref<any>(null);

watch(() => props.dialogVisible, (newValue, oldValue) => {
    visible.value = newValue;
    if (newValue) {
        nextTick(() => {
            if (props.checkItem.level < 2) {
                selectComponent.value?.getTreeList();
                if (props.type_dialog == 'add') {
                    ruleFormData.ruleForm = {
                        level: props.checkItem.level + 1,
                        name: "",
                        parentId: props.checkItem.id
                    }
                    if (props.checkItem.level == 1) {
                        ruleFormData.ruleForm.userList = [];
                    }
                    selectComponent.value?.empty();
                } else {
                    // ruleFormData.ruleForm = JSON.parse(JSON.stringify(props.dialogParams));
                    ruleFormData.ruleForm = {
                        id: props.dialogParams.id,
                        name: props.dialogParams.name,
                    }
                    if (props.dialogParams.userList && props.dialogParams.userList.length > 0) {
                        ruleFormData.ruleForm.userList = props.dialogParams.userList;
                        let userListArray = props.dialogParams.userList.map(function (item: any) {
                            return item.userId;
                        });
                        ruleFormData.selectData = userListArray
                    }
                }
                setTimeout(() => {
                    ruleFormRef.value?.clearValidate();
                }, 50);
            } else {
                selectComponent2.value?.getTreeList();
               
                if (props.type_dialog == 'add') {
                    ruleFormData.ruleForm2 = {
                        groupId: props.checkItem.id,
                        userList: []
                    }
                    console.log(' ruleFormData.ruleForm2', ruleFormData.ruleForm2);
                    
                    selectComponent2.value?.empty();
                }else{

                }
                setTimeout(() => {
                    ruleFormRef2.value?.clearValidate();
                }, 50);
            }

        })
    }
});

//校验班组组长
const checkRooms = (rule: any, value: any, callback: any) => {
    if (props.checkItem.level == 1) {
        if (!value || value.length == 0) {
            callback(new Error('请选择班组组长'))
        } else {
            callback()
        }
    } else {
        callback()
    }

}
//校验班组成员
const checkRooms2 = (rule: any, value: any, callback: any) => {
    if (props.checkItem.level == 2) {
        if (!value || value.length == 0) {
            callback(new Error('请选择班组成员'))
        } else {
            callback()
        }
    } else {
        callback()
    }

}

const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入使用类型名称', trigger: 'change' }],
    userList: [{ required: true, validator: checkRooms, trigger: 'change' }]
})

const rules2 = reactive<FormRules>({
    userList: [{ required: true, validator: checkRooms2, trigger: 'change' }]
})

//获取选择的班组组长
const getDeviceTypeId = (val: any) => {
    console.log('149', val);
    ruleFormData.ruleForm.userList = val;
}

const getDeviceTypeId2  = (val: any) => {
    ruleFormData.ruleForm2.userList = val;
}

//emit(父组件中的自定义方法)
const emit = defineEmits(['closeDialog', 'confirmDialog']);
//关闭弹窗
const handleClose = () => {
    emit("closeDialog");
}

//点击保存按钮
const handleConfirm = async (formEl: FormInstance | undefined) => {
    console.log('treeValue', treeValue);

    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (props.type_dialog == 'add') {
                group_Add();
            } else {
                group_edit();
            }
        } else {
            // console.log('error submit!', fields)
        }
    })


}

const handleConfirm2  = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // if (props.type_dialog == 'add') {
            //     add_Members();
            // }
            add_Members();
        } else {
            // console.log('error submit!', fields)
        }
    })


}

//新增班组成员
const add_Members = ()=>{
    addMembers(ruleFormData.ruleForm2).then(res => {
        ElMessage({
            message: '操作成功!',
            type: 'success',
        })
        //关闭弹窗且更新列表
        emit('confirmDialog');
    })
}

//新增班组类别或班组
const group_Add = () => {
    schedulingGroupAdd(ruleFormData.ruleForm).then(res => {
        ElMessage({
            message: '操作成功!',
            type: 'success',
        })
        //关闭弹窗且更新列表
        emit('confirmDialog');
    })
}

//编辑班组类别或班组
const group_edit = () => {
    schedulingGroupEdit(ruleFormData.ruleForm).then(res => {
        ElMessage({
            message: '操作成功!',
            type: 'success',
        })
        //关闭弹窗且更新列表
        emit('confirmDialog');
    })
}


</script>

<style scoped lang="scss">
.addDialog {
    :deep(.dialogAdd) {
        width: 448px;
        min-height: 235px;
        background: rgba(255, 255, 255, 1);
        border-radius: 2px;

        .el-dialog__header {
            padding: 0;

        }

        .el-dialog__body {
            padding: 0;

            .dialog_content {
                .dialog_header {
                    padding: 0;
                    height: 59px;
                    padding: 8px 32px 4px 62px;
                    line-height: 52px;
                    font-size: 16px;
                    font-weight: 400;
                    color: rgba(0, 0, 0, 1);
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    border-bottom: 1px dashed rgba(112, 105, 95, 1);

                    .title {
                        display: flex;
                        align-items: center;

                        img {
                            width: 4px;
                            height: 22px;
                            margin-right: 15px;
                        }

                    }

                    .close {
                        width: 25px;
                        height: 25px;
                        cursor: pointer;

                    }
                }

                .dialog_details {
                    padding: 25px 42px 0 42px;
                    font-size: 16px;
                    font-weight: 400;
                    letter-spacing: 0px;
                    line-height: 30px;
                    color: rgba(0, 0, 0, 1);

                    .details {
                        padding: 0 0 30px 0px;
                        align-items: center;

                        // &.details2 {
                        //     padding: 0 14px 25px 14px;
                        // }

                        .el-input-group--append {
                            .el-input__wrapper {
                                border-right: 0;
                            }

                            .el-input-group__append {
                                background-color: #fff;
                                padding: 0 5px;
                                border-radius: 0;
                            }
                        }

                    }

                }

            }
        }


    }

}

.dialog_form {
    display: block;

    :deep(.el-form-item) {
        margin-bottom: 22px;

        &.item_btn {
            padding-top: 25px;
        }

        &.is-required {
            .el-form-item__label::before {
                color: red;
                margin-top: 3px;
            }
        }

        .el-form-item__label {
            // width: 135px;
            width: auto;
            padding-right: 30px;
        }
    }

    .btn {
        width: 100%;
        text-align: right;
        padding-right: 35px;
    }
}
</style>